package com.wang.springbootinit.manager;

import com.wang.springbootinit.common.ErrorCode;
import com.wang.springbootinit.exception.BusinessException;
import com.wang.springbootinit.service.impl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

/**
 * 邮箱验证码
 */
@Component
@Slf4j
public class EmailSendCodeHandel {
    private static final Logger LOGGER = LoggerFactory.getLogger(EmailSendCodeHandel.class);

    @Autowired
    private JavaMailSender emailSender;

    private String myEmailHost = "wang546385234@qq.com";

    public void sendCode(String code, String email) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setSubject("找回密码"); // 发送邮件的标题
            message.setText("找回密码，验证码：" + code + "，切勿将验证码泄露给他人，本条验证码有效期2分钟。"); // 发送邮件的内容
            message.setTo(email); // 指定要接收邮件的用户邮箱账号
            message.setFrom(myEmailHost); // 发送邮件的邮箱账号，注意一定要和配置文件中的一致！
            LOGGER.info("sendCode email: {} ,code : {}", email, code);
            emailSender.send(message); // 调用send方法发送邮件即可
        } catch (MailException e) {
            LOGGER.error("sendCode exception: ", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
    }

}